<template>
    <div id="task-common-layout">
        <el-container class="container-box">
            <el-container v-loading="!isMounted">
                <el-header class="container-header">
                    <div class="container-header-title">
                        <span class="container-header-taskName" :title="taskInfo.name">
                            {{ taskInfo.name }}
                        </span>
                        <el-tag class="container-header-taskTag" :type="checkTaskStatus(taskInfo).type" effect="dark"
                            size="default">
                            {{ checkTaskStatus(taskInfo).title }}
                        </el-tag>
                    </div>
                    <div class="descriptions-box">
                        <el-descriptions title="" :column="3" size="default">
                            <el-descriptions-item :span='1' label="开始时间:">
                                {{ TimeYH2(taskInfo.starttime) }}
                            </el-descriptions-item>
                            <el-descriptions-item :span='1' label="结束时间:">
                                {{ TimeYH2(taskInfo.endtime) }}
                            </el-descriptions-item>
                            <el-descriptions-item :span='1' label="任务时长:">
                                {{ timeDiff(taskInfo.starttime, taskInfo.endtime) }}
                            </el-descriptions-item>
                            <el-descriptions-item :span='1' label="任务类型:">
                                {{ taskTypeInfoCfg[taskInfo.type || 'question'].title }}
                            </el-descriptions-item>
                            <el-descriptions-item v-show='taskInfo.reward' :span='1' label="任务奖励:">
                                {{ taskInfo.reward }}
                            </el-descriptions-item>
                            <el-descriptions-item v-show='taskInfo.remarks' :span='1' label="备注:">
                                {{ taskInfo.remarks }}
                            </el-descriptions-item>
                            <el-descriptions-item :span='3' label="完成条件:">
                                {{ taskTypeInfoCfg[taskInfo.type || 'question'].conditionText(taskInfo.questionnum || 0,
                taskInfo.questionac) }}
                            </el-descriptions-item>
                            <el-descriptions-item :span='3' label="我的进度:">
                                <!-- 控制进度条不换行显示 -->
                                <span style="display: inline-block;width: 45%;">
                                    <el-progress :percentage="myTaskInfo(taskInfo).num" />
                                </span>
                            </el-descriptions-item>
                            <el-descriptions-item :span="3" label="已完成:">
                                <span class="foot-todo">
                                    <span>
                                        <!-- 影响布局 需要改成瀑布流 -->
                                        <!-- <span class="container-content-cardFinishTag"
                                            v-for="(info, idx) in getFinishUser()">
                                            <span size="small" type="primary">
                                                {{ info.name }}
                                            </span>
                                        </span> -->
                                        <span class="container-content-cardFinishTag">
                                            <span size="small" type="primary">
                                                {{ getFinishUser().join('、') }}
                                            </span>
                                        </span>
                                    </span>
                                </span>
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>
                </el-header>
                <el-main class="padding0">
                    <!-- 中间tabs class="container-content-tabs-box"-->
                    <div class="">
                        <el-tabs v-model="activeName" class="" type="">
                            <el-tab-pane lazy :name="taskInfo.type">
                                <template #label>
                                    <el-icon>
                                        <List />
                                    </el-icon>
                                    &nbsp;<span>{{ taskTypeInfoCfg[taskInfo.type || 'question'].tabName }}</span>
                                </template>
                                <div class="container-content" v-if="activeName === Tabs.QUESTION">
                                    <QuestionTask :selectedTask="taskInfo" :taskTypeInfoCfg="taskTypeInfoCfg"
                                        :questions="questions">
                                    </QuestionTask>
                                </div>
                                <div class="container-content" v-else-if="activeName === Tabs.VIDEO">
                                    <VideoTask :selectedTask="taskInfo" :taskTypeInfoCfg="taskTypeInfoCfg"
                                        :courses="courses">
                                    </VideoTask>
                                </div>
                                <div class="container-content" v-else-if="activeName === Tabs.FILE">
                                    <FileTask :selectedTask="taskInfo" :taskTypeInfoCfg="taskTypeInfoCfg"
                                        :teamFiles="teamFiles">
                                    </FileTask>
                                </div>
                            </el-tab-pane>
                            <el-tab-pane lazy v-if="showRank" :name="Tabs.MEMBERTASKRANK">
                                <template #label>
                                    <el-icon>
                                        <TrendCharts />
                                    </el-icon>
                                    &nbsp;<span>完成情况</span>
                                </template>
                                <div class="container-content">
                                    <MemberTaskRank :selectedTask="taskInfo" :teamUsers="teamUsers"
                                        :questions="questions" :courses="courses" :teamFiles="teamFiles">
                                    </MemberTaskRank>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                    </div>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup lang="ts">
import { dayjs } from "element-plus";
import { computed, onMounted, reactive, ref } from 'vue';
import { useStore } from "vuex";
import {
    asyncselectteamjobrelations,
    asyncselectteamselectuser,
    asyncteamselectteamjob
} from '../../../api';
import { Storekey } from "../../../interface";
import Alymodel from '../../../mysql_interface/model';
import Studycodemodel from '../../../mysql_interface/studycodemodel';
import { JCTime } from "@/util/jianchatime";
import { TimeYH2 } from "../../../util/time";
import { TaskType } from '../team/type';
import FileTask from './fileTask.vue';
import MemberTaskRank from './memberTaskRank.vue';
import QuestionTask from './questionTask.vue';
import VideoTask from './videoTask.vue';

enum Tabs {
    QUESTION = "question",
    VIDEO = "video",
    FILE = "file",
    MEMBERTASKRANK = "memberTaskRank",
}
const taskTypeInfoCfg: Record<TaskType, { tabName: string, title: string, conditionText: (num: number, degree?: number) => string }> = {
    video: { tabName: "任务视频", title: '观看视频', conditionText: (num: number, degree?: number) => `观看${num}节课程视频, 且观看视频时长大于${degree}%` },
    question: { tabName: "任务题目", title: '题目练习', conditionText: (num: number, degree?: number) => `完成${num}题, 且代码题目测试点正确率${degree}%` },
    file: { tabName: "任务资料", title: '学习资料', conditionText: (num: number, degree?: number) => `学习${num}份资料` },
    // 默认
    undefined: { title: '任务类型', conditionText: (num: number, degree?: number) => `完成条件` },
}
const TaskStatusCfg: {
    [key: number]: {
        title: string, type: 'primary' | 'success' | 'info' | 'warning' | 'danger',
        bntText: string, show: boolean, disabled: boolean
    }
} = {
    0: { title: "未开始", type: "warning", bntText: "任务没有开始", show: true, disabled: true },
    1: { title: "已结束", type: "info", bntText: "任务已经结束", show: false, disabled: true },
    2: { title: "进行中", type: "success", bntText: "去完成", show: true, disabled: false }
}

const props = defineProps<{ ID?: number }>()
const store = useStore(Storekey)
const user = computed(() => {
    return store.state.user
})
const teamid = computed(() => {
    return user.value?.teamid;
});
const datenow = computed(() => {
    return store.state.time
})

const timer = ref(0)
const n = ref('结束')
const time = reactive<JCTime>({
    isok: false,
    d: 0,
    h: 0,
    s: 0,
    m: 0,
})
// 是否公开任务进度
const showRank = computed(() => {
    const { isopen } = taskInfo.value
    return user.value?.isAdmin ? true : isopen
})

const isMounted = ref(false)
onMounted(async () => {
    await start()
    isMounted.value = true
})
async function start() {
    await getTeamTask()
    // 团队成员
    teamUsers.value = await asyncselectteamselectuser({ teamid: teamid.value });
    // 完成情况
    const ret = await asyncselectteamjobrelations({
        _order: "teamjobid",
        teamid: teamid.value,
        teamjobid: props.ID,
        state: true,
    })
    taskFinishInfo.value = ret
}
// 查询条件
const offset = ref<number>(0)
const limit = ref<number>(9)
// 具体任务
const questions = ref<Studycodemodel.Iquestion[]>([])
const courses = ref<Alymodel.IMcourse[]>([])
const teamFiles = ref<Studycodemodel.Iteamfile[]>([])
const totalCount = ref<number>(0)
const taskInfo = ref<Studycodemodel.Iteamjob>({})
// 任务列表-匹配ID
async function getTeamTask() {
    let order = ['ID']
    const { rows, count, question, course, teamfile } = await asyncteamselectteamjob({
        ID: props.ID,
        _offset: offset.value,
        _limit: limit.value,
        teamid: teamid.value,
        _order: order,
        _sortable: "DESC"
    })
    questions.value = question.map(e => { return { ID: e.ID, name: e.name, label: e.label } })
    courses.value = course.map(e => { return { ID: e.ID, name: e.name } })
    teamFiles.value = teamfile.map(e => { return { ID: e.ID, name: e.name, size: e.size, url: e.url } })
    taskInfo.value = rows[0]
    totalCount.value = count
    activeName.value = taskInfo.value.type
}
const activeName = ref<Tabs>(taskInfo.value.type)
function checkTaskStatus(data: Studycodemodel.Iteamjob) {
    const { starttime, endtime } = data
    const n = dayjs().unix()
    if (n < dayjs(starttime).unix()) {
        return TaskStatusCfg[0]
    }
    if (n > dayjs(endtime).unix()) {
        return TaskStatusCfg[1]
    }
    return TaskStatusCfg[2]
}
// endTime - startTime
function timeDiff(a?: Date | string, b?: Date | string) {
    const t = dayjs(b).toDate().getTime() - dayjs(a).toDate().getTime()
    let n: string | number = (t / 60 / 60 / 1000).toFixed(1)
    if (Number(n) === Math.floor(Number(n))) {
        n = Math.floor(Number(n))
    }
    return n + '小时'
}

const teamUsers = ref<Studycodemodel.Iteamuser[]>([])
// 任务完成情况 userid: 100007, teamjobid: 11048, state: true, count: 2
const taskFinishInfo = ref<Studycodemodel.Iteamjobrelation[]>([])
// 根据任务id,任务目标数 获取已完成成员
function getFinishUser() {
    const { ID: taskId, questionnum } = taskInfo.value
    const tmp: string[] = []
    taskFinishInfo.value.forEach((e, i) => {

        if (e.count < questionnum) {
            return
        }

        const user = teamUsers.value.find(u => u.userid === e.userid) || {}
        let name = user?.user?.name
        tmp.push(name)
    })
    // 已完成 只显示三个 后面是的显示 等X人
    const showCount = 3
    const n = tmp.length - showCount
    return n > 0 ? [...tmp.splice(0, showCount), `……等${n}人`] : [...tmp.splice(0, showCount)]
}
// 我的任务完成情况 
function myTaskInfo(row: Studycodemodel.Iteamjob) {
    const questionnum = row.questionnum || 1
    const n = row.teamjobrelation?.filter(e => e.userid === user.value?.ID)
    if (n?.length) {
        const _n = n.filter(e => !e.state)
        const num = Math.floor(n.filter(e => e.state).length / questionnum * 100)
        return {
            isshow: true,
            num: num > 100 ? 100 : num,
            next: _n
        }
    }
    return {
        isshow: false,
        num: 0
    }
}

// 距离任务结束
const duration = ref<{ endtime: Date, starttime: Date }>()

</script>

<style scoped>
.container-box {
    padding: var(--container-margin) 5% 0;
    margin: var(--container-margin) 0rem 0 0rem;
    /* 外边距 */
    --container-margin: 20px;
    --container-header-height: 23vh;
    --container-bg-color: #fff;

    --descriptions-bg-color: #fafafa;
}

.container-header {
    height: var(--container-header-height);
    min-height: var(--container-header-height);
    background: var(--container-bg-color);
    width: 100%;
    padding: var(--container-margin);

    box-shadow: var(--container-box-shadow);
    border-radius: var(--container-border-radius);
}

.container-header-title {
    display: flex;
    align-items: center;
    margin-bottom: var(--container-margin);
    padding: 0 var(--container-margin);
}

.container-header-taskName {
    /* width: 90%; */
    font-weight: bolder;
    font-size: 1.5rem;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.container-header-taskTag {
    margin-left: 10px;
    /* display: inline-block; */
}

.descriptions-box {
    padding: 10px 20px;
    margin-left: 0;
    font-size: 14px;
    background: var(--descriptions-bg-color);
    box-shadow: var(--container-box-shadow);
    border-radius: var(--container-border-radius);
}

/* 激活码 */
.invitation,
.tabs-box {
    height: 80%;
    display: flex;
    flex-wrap: wrap;
}

.invitation {
    flex-direction: column;
    justify-content: center;
    height: 50px;
}

.invitation-desc {
    margin-bottom: 10px;
}

.invitation-form {}

/* 下发文件下载 */
.file-download-btn,
.file-download-btn a {
    color: #000;
    border-radius: 8px;
}

.file-download-btn:hover a {
    color: #fff;
}

.download-file {}

.container-content-cardFinishTag {
    display: inline-block;
    margin: 0.1rem 0.1rem 0;
}

.container-content-tabs-box {
    background: var(--container-bg-color);
    margin-top: var(--container-margin);
    padding: 1px var(--container-margin);
    box-shadow: var(--container-box-shadow);
    border-radius: var(--container-border-radius);
}

/* 报名后的tabs */
.tabs-box {
    justify-content: space-between;
    align-items: center;
}

.container-content {
    background: var(--container-bg-color);
    margin-top: var(--container-margin);
    padding: var(--container-margin);
    min-width: 80%;
    /* TODO */
    /* height: calc(100vh - 64px - var(--container-margin)* 5 - var(--container-header-height)) */
}

.acvitity-desc {
    button {
        font-weight: bolder;
        width: 160px;
        border-radius: 8px;
    }
}

/*  */
.btn-tab {
    font-weight: bolder;
    width: 160px;
    border-radius: 8px;
}


.aside-container-box {
    /* padding: var(--container-margin); */
}

.aside-card-title {
    font-weight: bolder;
    font-size: 1.5rem;
}

.aside-card-content {
    /* padding-top: var(--container-margin); */
}

/* 状态 */
.info,
.primary,
.danger,
.success {
    width: 44px;
    height: 24px;
    color: #fff;
    display: inline-block;
    text-align: justify;
    font-size: 12px;
    font-weight: 400;
    line-height: 24px;
    text-align: center;
    border-radius: 5px;
}

/* 赛事结束-已结束 */
.info {
    background-color: rgba(236, 128, 141, 1);
}

/* 立即报名-报名中 */
.primary {
    background: rgb(112, 182, 3);
    /* transform: translateY(-3px); */
}

/* 即将开赛-未开始 */
.danger {
    background: rgb(170, 170, 170);
    /* transform: translateY(-3px); */
}

/* 进入任务-任务中 */
.success {
    background: var(--color-cheng);
    /* transform: translateY(-3px); */
}
</style>

<style>
/* 自定义.el-descriptions 样式 */
#app.ojSass #task-common-layout .descriptions-box .el-descriptions {
    width: 80%;
}

#app.ojSass #task-common-layout .descriptions-box .el-descriptions__header {
    margin: 0;
}

#app.ojSass #task-common-layout .descriptions-box .el-descriptions__body {
    border-left: 4px solid var(--sass-color-blue);
    background: var(--descriptions-bg-color) !important;
    padding: 0 20px;
}

#app.ojSass #task-common-layout .descriptions-box .el-descriptions__body .el-descriptions__cell {
    padding-bottom: 4px;
}

/* 自定义tabs样式 */
#app.ojSass #task-common-layout .el-tabs__header {
    background: var(--container-bg-color);
    border: none;
    margin: 0;

    background: var(--container-bg-color);
    margin-top: var(--container-margin);
    padding: 1px var(--container-margin);
    box-shadow: var(--container-box-shadow);
    border-radius: var(--container-border-radius);
}

#app.ojSass #task-common-layout .el-tabs__nav-wrap:after {
    background-color: transparent;
    height: 0;
}

#app.ojSass #task-common-layout .el-tabs__item {
    height: 50px;
    line-height: 50px;
}
</style>